package complain;

import until.DBUtil;
import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ComplaintPanel extends JPanel {
    public ComplaintPanel() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 标题
        JLabel label = new JLabel("异常柜门投诉", SwingConstants.CENTER);
        label.setFont(new Font("微软雅黑", Font.BOLD, 24));
        label.setForeground(new Color(44, 62, 80));
        label.setBorder(BorderFactory.createEmptyBorder(30, 0, 10, 0));
        add(label, BorderLayout.NORTH);

        // 表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(15, 15, 15, 15);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // 柜门编号
        JLabel lockerLabel = new JLabel("柜门编号：");
        lockerLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(lockerLabel, gbc);

        JTextField lockerField = new JTextField(20);
        lockerField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        gbc.gridx = 1;
        formPanel.add(lockerField, gbc);

        // 联系电话
        JLabel phoneLabel = new JLabel("联系电话：");
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(phoneLabel, gbc);

        JTextField phoneField = new JTextField(20);
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        gbc.gridx = 1;
        formPanel.add(phoneField, gbc);

        // 问题描述
        JLabel descLabel = new JLabel("问题描述：");
        descLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(descLabel, gbc);

        JTextArea descArea = new JTextArea(5, 20);
        descArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        descArea.setLineWrap(true);
        descArea.setWrapStyleWord(true);
        JScrollPane descScroll = new JScrollPane(descArea,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        gbc.gridx = 1;
        formPanel.add(descScroll, gbc);

        add(formPanel, BorderLayout.CENTER);

        // 提交按钮
        JButton submitBtn = new JButton("提交投诉");
        submitBtn.setFont(new Font("微软雅黑", Font.BOLD, 16));
        submitBtn.setBackground(new Color(255, 87, 34));
        submitBtn.setForeground(Color.WHITE);
        submitBtn.setFocusPainted(false);
        submitBtn.setPreferredSize(new Dimension(140, 40));

        submitBtn.addActionListener(e -> {
            String locker = lockerField.getText().trim();
            String phone = phoneField.getText().trim();
            String desc = descArea.getText().trim();

            // 表单验证
            if (locker.isEmpty() || phone.isEmpty() || desc.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写完整信息！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!locker.matches("\\d+")) {
                JOptionPane.showMessageDialog(this, "柜门编号必须是数字！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!phone.matches("^1[3-9]\\d{9}$")) {
                JOptionPane.showMessageDialog(this, "请输入合法的手机号码！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            // 插入投诉记录，并设置柜门为故障，记录原状态
            try (Connection conn = DBUtil.getConnection()) {
                conn.setAutoCommit(false); // 开启事务

                int lockerId = Integer.parseInt(locker);

                // 1. 查询当前柜门状态
                String queryStatus = "SELECT status FROM lockers WHERE id = ?";
                PreparedStatement ps0 = conn.prepareStatement(queryStatus);
                ps0.setInt(1, lockerId);
                ResultSet rs = ps0.executeQuery();

                if (!rs.next()) {
                    JOptionPane.showMessageDialog(this, "柜门编号不存在！", "错误", JOptionPane.ERROR_MESSAGE);
                    conn.rollback();
                    return;
                }

                String originalStatus = rs.getString("status");
                ps0.close();

                // 2. 插入投诉记录，记录原状态
                String sql1 = "INSERT INTO complaints (locker_id, original_status, phone, reason, status, report_time) " +
                        "VALUES (?, ?, ?, ?, '待处理', NOW())";
                PreparedStatement ps1 = conn.prepareStatement(sql1);
                ps1.setInt(1, lockerId);
                ps1.setString(2, originalStatus);
                ps1.setString(3, phone);
                ps1.setString(4, desc);
                ps1.executeUpdate();

                // 3. 更新柜门状态为“故障”
                String sql2 = "UPDATE lockers SET status = '故障' WHERE id = ?";
                PreparedStatement ps2 = conn.prepareStatement(sql2);
                ps2.setInt(1, lockerId);
                ps2.executeUpdate();

                conn.commit(); // 提交事务

                ps1.close();
                ps2.close();

                JOptionPane.showMessageDialog(this, "投诉已提交，柜门已标记为故障！", "成功", JOptionPane.INFORMATION_MESSAGE);
                lockerField.setText("");
                phoneField.setText("");
                descArea.setText("");
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "提交失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        JPanel btnPanel = new JPanel();
        btnPanel.setBackground(Color.WHITE);
        btnPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 30, 0));
        btnPanel.add(submitBtn);

        add(btnPanel, BorderLayout.SOUTH);
    }
}
